const Koa = require("koa")
const Router = require("koa-router")
const static = require("koa-static")
const jwt = require("jsonwebtoken")
const parser = require("koa-bodyparser")
const { exec } = require('./db')
const key = "wang"

const app = new Koa()
const router = new Router()

app.use(static(__dirname + "/views"))
app.use(parser())

router.post("/login", async (ctx) => {
   
    const { userName, passWord } = ctx.request.body
    // 在数据库中匹配
    const data = await exec(`select * from user where userName='${userName}' and passWord='${passWord}'`)
    if (data.length > 0) {
        const token = jwt.sign({
            userName: data[0].userName,
            userId: data[0].userId
        }, key, {
            expiresIn: '1h'
        })
        ctx.body = {
            message: "登录成功！",
            token
        }
    } else {
        ctx.body = {
            message: "账号密码不匹配"
        }
    }
})

router.get("/getGoods", isLogin, async (ctx) => {
    const data = await exec("select * from goods")
    ctx.body = {
        message: "获取数据成功",
        data
    }
})



router.delete("/delGoods/:id", isLogin, auth, async (ctx) => {
   
    const { id } = ctx.request.params
    await exec(`delete from goods where id=${id}`)
    ctx.body = {
        message: "删除成功",
        code: 0
    }
})


async function isLogin(ctx, next) {
    const { token } = ctx.request.headers
    if (token) {
        if (jwt.verify(token, key)) {
            await next()
        } else {
            ctx.body = {
                message: "登录过期"
            }
        }
    } else {
        ctx.body = {
            message: "请先登录"
        }
    }
}


async function auth(ctx, next) {
    const { token } = ctx.request.headers
    const data = jwt.verify(token, key)
    const { userId } = data

    if (userId === 0) {
        await next()
    } else {
        ctx.body = {
            message: "权限不足"
        }
    }
}

app.use(router.routes())

app.listen(5678, () => {
    console.log("http://127.0.0.1:5678")
})